<?php

namespace App\Models;

class Praises extends Base
{

    protected $table = 'praises';
    public $timestamps = false;
    protected $fillable = [
        'id','userid','newid'
    ];

    public function article(){
        return $this->belongsTo('App\Models\News', 'newid', 'id');
    }

    public function user(){
        return $this->belongsTo('App\Models\Users', 'userid', 'id');
    }

    protected function list($params, $limit = 10){
        $data = $this->where(function ($query) use ($params) {
                if(isset($params['userid']) && $params['userid']){
                    $query ->where('userid',$params['userid']);
                }
            })->with(['article' => function ($query) {
                $query->select(['id','title','summary','view','created_at','thumb','cateid','author_id','status','catepid','praise'])
                    ->with(['cateChild' => function ($query) {
                        $query->select(['id','name'])->get();
                    }])->get();
            }])->with(['user' => function ($query) {
                $query->select(['id','truename','avatar'])->get();
            }])
            ->orderBy('id','desc')
            ->paginate($limit)
            ->toArray();
        return $data;
    }


    protected function incPraise($id){
        $info = News::findOrFail($id);
        $pInfo = $this->where('newid',$info['id'])->where('userid',auth()->user()->id)->first();
        if($pInfo){
            return $info['praise'];
        }

        //增加文章点赞次数
        $info->increment('praise');

        //增加点赞记录
        $insert = [
            'userid' => auth()->user()->id,
            'newid'  => $info['id']
        ];
        $this->create($insert);

        //增加积分记录
        $setting = Configs::info('integral');
        $key = date('Y-m-d').'-'.auth()->user()->id;
        $dayPraise = (int)cache()->get($key);
        if($dayPraise < $setting['praise_day']){
            auth()->user()->increment('integral',$setting['praise']);
            $num = $dayPraise + 1;
            cache()->put($key,$num,60*60*24);
        }
        return $info['praise'];
    }
}
